package com.cxd.app.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.cxd.app.entity.InvestPulished;
import com.cxd.app.entity.base.LogPageVisitBase;
import com.cxd.app.service.UserService;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.controller.BaseController;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.IdGenerator;
import com.cxd.base.util.ParamUtil;

/**
 * 活动API
 * @author wtj
 * @date 2016年5月30日上午9:53:48
 * @company CXD
 * @version [Copyright (c) 2016 V001]
 */


@Controller("ActivityController")
@RequestMapping("activityc")
public class ActivityController extends BaseController{
	@Resource
	public BeanTools bt;
	
	@Resource
	public UserService userService;
	
	@RequestMapping(value = "visit_log", method = {RequestMethod.GET,RequestMethod.POST })
	public void visit_log(HttpServletRequest request,HttpServletResponse response,String pageFlag,String pageWidethHeight,String pageHref,String ua)throws IOException {
		String info = String.format("pageFlag:%s,pageWidethHeight:%s,pageHref:%s,ua:%s", pageFlag,pageWidethHeight,pageHref,ua);
		JSONObject json = new JSONObject();
		super.requestLog("visit_log",info);
		try {
			LogPageVisitBase lpvb = new LogPageVisitBase();
			lpvb.setId(IdGenerator.randomUUID());
			lpvb.setCtime(new Date());
			lpvb.setPageFlag(pageFlag);
			lpvb.setPageHref(pageHref);
			lpvb.setPageWidethHeight(pageWidethHeight);
			lpvb.setUa(ua);
			bt.add(lpvb);
		} catch(CxdException e){
			super.cxdJsonException(json, e,info);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
	}
	
	/**
	 * top 10 接口
	 * @author wtj
	 * @date 2016年5月30日上午9:53:48
	 * @param request
	 * @param response
	 * @param date 	参数格式：201605
	 * @throws IOException
	 */
	@RequestMapping(value = "top10", method = {RequestMethod.GET,RequestMethod.POST })
	public void login(HttpServletRequest request,HttpServletResponse response,String date)throws IOException {
		JSONObject json = new JSONObject();
		try {
			ParamUtil.notNullParam("日期:"+date);
			String sql = "select t.user_id as user, sum(t.money) as tmoney  from invest t "
					+ "where  date_format(t.time, '%Y%m') = '"+date+"' and t.status<>'cancel' group by t.user_id order by sum(t.money) desc limit 10";
			List<Map<String,Object>> list = bt.queryListMap(sql);
			List<InvestPulished> ipsList = new ArrayList<InvestPulished>();
			for (Map<String,Object> map : list) {
				InvestPulished ips = new InvestPulished(encryptUserName((String) map.get("user")),(Double) map.get("tmoney"), 0.0);
				ipsList.add(ips);
			}
			json.put("rlist", ipsList);
			if(json.get("status")==null){
				this.jsonMsg(json, 200, "数据获取成功");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,date);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(request,response, json);
	}
	
	/**
	 * 加密用户名
	 * @param string
	 * @return
	 */
	private String encryptUserName(String str) {
		if(str==null||str=="")
			return "";
		if(str.length()<6){
			return str.substring(0,2)+"***";
		}else{
			return str.substring(0,2)+"***"+str.substring(str.length()-3);
		}
	}
	
	
	/**
	 * 判断手机是否可用
	 * @author wtj
	 * @date 2016年1月21日下午2:44:48
	 * @param response
	 * @param username
	 * @throws IOException
	 */
	@RequestMapping(value = "is_use_phone", method = {RequestMethod.GET,RequestMethod.POST })
	public void isUsePhone(HttpServletRequest request,HttpServletResponse response,String phoneNo)throws IOException {
		JSONObject json = new JSONObject();
		try {
			ParamUtil.notNullParam("手机号:"+phoneNo);
			int countInt = bt.queryForInt("select count(0) from user where id='"+phoneNo.toString()+"' or username='"+phoneNo.toString()+"' or mobile_number='"+phoneNo.toString()+"'");
			if(countInt==0){
				json.put("status", 200);
				json.put("msg", "成功");
			}else{
				json.put("status", 500);
				json.put("msg", "此号码已绑定其他账号");
			}
		} catch(CxdException e){
			super.cxdJsonException(json, e,phoneNo);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(request,response, json);
	}
	
	/**
	 * 判断验证码时候正确
	 * @author wtj
	 * @date 2016年6月3日上午9:38:38
	 * @param request
	 * @param response
	 * @param code
	 * @throws IOException
	 */
	@RequestMapping(value = "check_pic_code", method = {RequestMethod.GET,RequestMethod.POST })
	public void picCode(HttpServletRequest request,HttpServletResponse response,String code,String phone) throws IOException{
        // 将四位数字的验证码保存到Session中。
//        HttpSession session = request.getSession(true);
		JSONObject json = new JSONObject();
//		String redCode=(String) session.getAttribute("REG_CODE");
//		System.out.println(request.getSession()+"-------------------"+redCode +"------------"+code);
		String redCode = CodeController.phoneMap.get(phone.trim());
		if(code.equals(redCode)){
			json.put("status", "200");
			json.put("msg", "验证码正确");
		}else{
			json.put("status", "500");
			json.put("msg", "验证码错误");
		}
		super.responseSendMsg(request,response, json);
	}
	
	/**
	 * 注册发送验证码
	 * @param request
	 * @param response
	 * @param value
	 * @throws IOException
	 */
	@RequestMapping(value = "send_sms_code", method = {RequestMethod.GET,RequestMethod.POST })
	public void registerSendVerificationCode(HttpServletRequest request,HttpServletResponse response,String phoneNo)throws IOException {
		JSONObject json = new JSONObject();
		try {
			if(StringUtils.isBlank(phoneNo)){
				throw new CxdException("手机不允许为空");
			}
			int countInt = bt.queryForInt("select count(0) from user where id='"+phoneNo+"' or mobile_number='"+phoneNo+"'");
			if(countInt > 0){
				throw new CxdException("用户已经存在");
			}
			userService.verifyAuthInfo(json,phoneNo);
			json.put("status", 200);
			json.put("msg", "成功");
		} catch(CxdException e){
			super.cxdJsonException(json, e,phoneNo);
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		super.responseSendMsg(request,response, json);
	}
	
	/**
	 * 保存注册
	 * @author wtj
	 * @date 2016年6月3日上午10:09:47
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param authCode
	 * @param password
	 * @param sourceCode
	 * @param sourceType
	 * @param referrer
	 * @throws IOException
	 */
	@RequestMapping(value = "save_reg", method = {RequestMethod.GET,RequestMethod.POST })
	public void save_reg(HttpServletRequest request,HttpServletResponse response,String phoneNo,String authCode,String password,String sourceCode,String sourceType,String referrer)throws IOException {
		phoneNo = (phoneNo==null?"":phoneNo.trim());
		authCode = (authCode==null?"":authCode.trim());
		sourceCode = (sourceCode==null?"":sourceCode.trim());
		sourceType = (sourceType==null?"":sourceType.trim());
		referrer = (referrer==null?"":referrer.trim());
		logger.info(String.format("{phoneNo:%s,authCode:%s,sourceCode:%s,sourceType:%s}",phoneNo,authCode,sourceCode,sourceType));
		JSONObject json = new JSONObject();
		try {
			ParamUtil.notNullParam("手机号:"+phoneNo,"验证码:"+authCode,"密码:"+password);
			json.put("phoneNo", phoneNo);
			json.put("userName",phoneNo);
			json.put("password", password);
			json.put("authCode", authCode);
			json.put("referrer", referrer);
			json.put("sourceCode", sourceCode);
			json.put("sourceType", sourceType);
			
			userService.register(request,json,json.toJSONString());
			json.put("status", 200);
			json.put("msg", "用户注册成功");
		} catch(CxdException e){
			super.cxdJsonException(json, e,json.toJSONString());
		}catch (Exception e) {
			super.jsonException(json, e, logger);
		}
		json.remove("phoneNo");
		json.remove("userName");
		json.remove("password");
		json.remove("authCode");
		json.remove("referrer");
		json.remove("sourceCode");
		json.remove("sourceType");
		super.responseSendMsg(request,response, json);
	}
}
